
package cn.platform.service;

import cn.platform.mapper.AdminMapper;
import cn.platform.mapper.ParentMapper;
import cn.platform.mapper.StudentMapper;
import cn.platform.mapper.TeacherMapper;
import de.mkammerer.argon2.Argon2;
import de.mkammerer.argon2.Argon2Factory;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import cn.platform.entity.UserAccount;
import cn.platform.request.IdentifyRequest;
import cn.platform.response.AResponse;
import cn.platform.response.LoginResponse;
import cn.platform.util.identify.SessionToken;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class IdentifyService {

    @Resource
    private TeacherMapper teacherMapper;

    @Resource
    private AdminMapper adminMapper;

    @Resource
    private ParentMapper parentMapper;

    @Resource
    private StudentMapper studentMapper;

    private final Argon2 argon2 = Argon2Factory.create();

    /**
     * 用户登录，账号密码正确则返回令牌，否则令牌为null
     */
    public AResponse tryLogin(IdentifyRequest identifyRequest) {
        AResponse res = new AResponse();
        LoginResponse loginResponse = new LoginResponse();
        res.setData(loginResponse);

        List<UserAccount> list = new ArrayList<>();
        switch (identifyRequest.getRole()) {
            case "admin":
                list = adminMapper.identify(identifyRequest);
                break;
            case "teacher":
                list = teacherMapper.identify(identifyRequest);
                break;
            case "parent":
                list = parentMapper.identify(identifyRequest);
                break;
            case "student":
                list = studentMapper.identify(identifyRequest);
                break;
        }

        if (!list.isEmpty()) {
            UserAccount userAccount = list.getFirst();
            String userHash = userAccount.getPassword();
            boolean success = argon2.verify(userHash, identifyRequest.getPassword().toCharArray());
            if (success) {
                String token = SessionToken.login(userAccount);
                loginResponse.setToken(token);
                res.setSuccess(true);
                log.info("登录成功，角色：{}, 用户名：{}", userAccount.getRole(), userAccount.getUsername());
            }
            else {
                res.setMessage("密码错误");
                log.info("密码错误, 用户名：{}，密码：{}", userAccount.getUsername(), userAccount.getPassword());
            }
        }
        else {
            res.setMessage("用户名或角色错误");
            log.info("用户名或角色错误，角色：{}, 用户名：{}", identifyRequest.getRole(), identifyRequest.getUsername());
        }
        return res;
    }

    /**
     * 会话令牌有效性验证
     */
    public AResponse checkToken(){
        Map<String, Boolean> map = new HashMap<>();
        AResponse res = new AResponse();
        try{
            SessionToken.checkLogin();
        }
        catch(Exception e){
            log.info("检查token非法：{}", e.getMessage());
            map.put("isValid", false);
            res.setData(map);
            return res;
        }
        log.info("用户：{}，检查token合法", SessionToken.getUserAccount().getUsername());
        map.put("isValid", true);
        res.setData(map);
        return res;
    }

    /**
     * 登出
     */
    public AResponse logout(){
        Map<String, Boolean> map = new HashMap<>();
        String username = SessionToken.getUserAccount().getUsername();
        AResponse res = new AResponse();
        try{
            //SessionToken.checkLogin();
            SessionToken.logout();
        }
        catch(Exception e){
            log.info("用户：{}，登出失败：{}", SessionToken.getUserAccount().getUsername() ,e.getMessage());
            map.put("success", false);
            res.setData(map);
            return res;
        }
        log.info("用户：{}，登出成功", username);
        map.put("success", true);
        res.setData(map);
        return res;
    }
}
